package inits

import (
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/google/uuid"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"srv-server/basic/config"
	"srv-server/basic/consul"
	"srv-server/basic/global"
)

func InitAll() {
	NaconsInit()
	ConslInit()
	MysqlInit()
	RedisInit()
}

func NaconsInit() {
	data := config.NacosConf
	clientConfig := constant.ClientConfig{
		NamespaceId:         data.NamespaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      data.IpAddr,
			ContextPath: "/nacos",
			Port:        uint64(data.Port),
			Scheme:      "http",
		},
	}
	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	content, _ := configClient.GetConfig(vo.ConfigParam{
		DataId: data.DataId,
		Group:  data.Group})

	app := config.Conf
	json.Unmarshal([]byte(content), &app)
	config.Conf = app
	fmt.Println(config.Conf)

}

func ConslInit() {

	sul, _ := consul.ConSul("14.103.143.155", 8500)
	serviceId := uuid.NewString()
	register := consul.ConsulRegister{
		ID:      serviceId,
		Name:    config.Conf.Mysql.Username,
		Tags:    []string{"srv-server", "srv"},
		Port:    config.Conf.Mysql.Port,
		Address: config.Conf.Mysql.Host,
	}

	sul.ServiceRegister(register)

}

func MysqlInit() {
	var err error
	data := config.Conf.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", data.Username, data.Password, data.Host, data.Port, data.Database)

	//dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("数据库连接失败")

	} else {
		log.Println("数据库连接成功")
	}
}
func RedisInit() {
	global.Rdb = redis.NewClient(&redis.Options{
		Addr:     config.Conf.Redis.Addr,
		Password: config.Conf.Redis.Password, // no password set
		DB:       config.Conf.Redis.DB,       // use default DB
	})
}
